<template>
  <div>
    <el-input disabled :value="$route.query.roleName"></el-input>
    <!-- default-expand-all  全部展开 -->
    <el-tree style="margin: 20px 0" ref="tree" :data="allPermissions" node-key="id" show-checkbox 
      :props="defaultProps" />
    <el-button :loading="loading" type="primary" @click="save">保存</el-button>
    <el-button @click="$router.replace({ name: 'Role' })">取消</el-button>
  </div>
</template>
<script>
export default {
  name: 'RoleAuth',
  data(){return {
    allPermissions:[],
    defaultProps:{
      children: 'children',
          label: 'name'
    },
    loading:false,
  }},
  mounted(){
   this.initTreeData();
  },
  methods:{
    async initTreeData(){
      const roleId= this.$route.params.id;
      const result= await this.$API.permission.toAssign(roleId);
      this.allPermissions=result.data.children;
      const selectedIds= this.getCheckedIds(this.allPermissions);
      this.$refs.tree.setCheckedKeys(selectedIds)
    },
    //获取选中项的Ids
    getCheckedIds(auths,initArr=[]){
      return auths.reduce((pre, item) => {
          if (item.select && item.level===4) {
            pre.push(item.id)
          } else if (item.children) {
            this.getCheckedIds(item.children, initArr)
          }
          return pre
        }, initArr)
    },
    //保存
   async save(){
        /* 
        vue elementUI tree树形控件获取父节点ID的实例
        修改源码:
        情况1: element-ui没有实现按需引入打包
          node_modules\element-ui\lib\element-ui.common.js    25382行修改源码  去掉 'includeHalfChecked &&'
          // if ((child.checked || includeHalfChecked && child.indeterminate) && (!leafOnly || leafOnly && child.isLeaf)) {
          if ((child.checked || child.indeterminate) && (!leafOnly || leafOnly && child.isLeaf)) {
        情况2: element-ui实现了按需引入打包
          node_modules\element-ui\lib\tree.js    1051行修改源码  去掉 'includeHalfChecked &&'
          // if ((child.checked || includeHalfChecked && child.indeterminate) && (!leafOnly || leafOnly && child.isLeaf)) {
          if ((child.checked || child.indeterminate) && (!leafOnly || leafOnly && child.isLeaf)) {
        */
        var ids = this.$refs.tree.getCheckedKeys().join(",");
        this.loading = true
        const resut =await this.$API.permission.doAssign(this.$route.params.id, ids);
        this.loading=false;
        const roleName = this.$route.query.roleName
        const roles = this.$store.getters.roles
        this.$router.replace('/acl/role/list', ()=>{
          if (roles.includes(roleName)) {
              window.location.reload()
            }
        });


    },
  },
}
</script>